import requests
import re
import rsa
from Crypto.PublicKey import RSA
import base64
import json

person = requests.Session()
person.headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        # "Host": "q.yiban.cn",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                      "(KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
}


# 登录易班
def login(user, password):

    login_page_url = "https://www.yiban.cn/login"
    login_page_res = person.get(url=login_page_url)
    # print(login_page_res.text)
    # 获取公钥并加密
    public_key = re.findall(r"BEGIN PUBLIC KEY-----\sM(.*)-----END PUBLIC KEY", login_page_res.text, re.S)[0]
    public_key = '-----BEGIN PUBLIC KEY-----\nM' + public_key + '-----END PUBLIC KEY-----'
    print(public_key)
    rsa_key = RSA.importKey(public_key)
    x = rsa.encrypt(password.encode(), rsa_key)
    rsa_pass = base64.b64encode(x).decode()
    print(rsa_pass)
    # 获取时间戳
    keys_time = re.findall(r"data-keys-time='(.*?)'", login_page_res.text)[0]
    print(keys_time)
    check_in = captcha()
    # random = time.time()
    # random = round(random, 2)  # 只取两位小数

    # 登录易班
    login_url = "https://www.yiban.cn/login/doLoginAjax"
    login_data = {
        "account": user,
        "password": rsa_pass,
        "captcha": check_in,
        "keysTime": keys_time
    }
    login_res = person.post(url=login_url,  data=login_data)

    # 获取登录结果
    getlogin_url = "http://www.yiban.cn/ajax/my/getLogin"
    getlogin_data = {
        "": ""
    }
    getlogin_res = person.post(url=getlogin_url, data=getlogin_data)
    print(getlogin_res)
    getlogin_res_content = getlogin_res.json()
    print(getlogin_res_content)


def captcha():
    captcha_check_url = "https://www.yiban.cn/captcha/index?Tue%20Dec%2004%202018%2000:01:2" \
                        "6%20GMT+0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)"
    captcha_check_respond = person.get(url=captcha_check_url)
    print(captcha_check_respond)
    captcha_content = captcha_check_respond.content  # 转换类型
    fb = open('captcha.jpg', 'wb')  # 把字节类型转换为图片文件
    fb.write(captcha_content)
    fb.close()
    check_in = input("请输入图片验证码>>>:")
    return check_in


if __name__ == '__main__':
    user = input("请输入账号>>>: ")
    password = input("请输入密码>>>: ")
    login(user, password)